#!/usr/bin/env python
# -*- coding:utf-8 -*- #
from popcan.helper.requesthelper import getParam as _p,JsonResult,ext
from popcan.biz.agents import DailyAgent
import traceback
import logging

agent = DailyAgent()
logger = logging.getLogger('image-server.upload')

def upload(request):
    errlist = ['userId_empty','file_empty','file_ext_none','file_type_unsupported','file_too_large']
    userId = _p(request,'userId')
    stream = request.FILES.get('file',None)
    if userId is None:
        return JsonResult().fail('userId_empty','userId must not be empty').response()
    if stream is None:
        return JsonResult().fail('file_empty','file must notb empty').response()
    logger.info('%s=%s' % (userId,stream.name))
    exttype = ext(stream.name)
    if not exttype:
        return JsonResult().fail('file_ext_none','file name has no extension name').response()
    if not agent.allowed(exttype):
        return JsonResult().fail('file_type_unsupported','file type %s has not yet supported' % exttype).response()
    if agent.getMaxSize() < stream.size:
        return JsonResult().fail('file_too_large','upload max size %sM' % (agent.getMaxSize()/1024/1024)).response()
    try:
        ret = JsonResult()
        urls = agent.saveFile(userId,stream)
        ret.retdata['furl'],ret.retdata['turl'] = urls
        ret.retdata['errlist'] = errlist
        return ret.response()
    except:
        traceback.print_exc()
        return JsonResult().fail('unknown_error', 'upload exception occured').response()